package proj1;

import java.util.ArrayList;

public class SemAnalyzer {
	// helper tree
	ArrayList<String> helperTree = new ArrayList<String>();
	// new tree - what we will use to get html tags
	ArrayList<String> newTree = new ArrayList<String>();
	// temp arraylist (stack) to put parse tree in
	// use this to check for sem errors & then write to file
	ArrayList<String> temp = new ArrayList<String>();
	// instance variables
	String mkt;
	String m;
	boolean found = false;
	String n;
	String o;
	
	public void generateDoc(ArrayList<String> tree){
		for(int i = 0; i < tree.size(); i ++){
			String mdt = tree.remove(i);
			if(mdt.contains("- ")){ // token is use variable
				while(helperTree.size() > 0 && !found){ // check to see if var name is in helperTree
					m = helperTree.remove(helperTree.size() - 1); // pop off helperTree
					if(m.contains(" = ") && m.contains(mdt.substring(mdt.lastIndexOf('-') + 2, mdt.length() - 1))){ // if pop is a var declaration token & equals var declaration name 
						found = true;
						mdt = m.substring(m.lastIndexOf('=') + 2, m.length() - 1); // resolve var to its value
						helperTree.add(m); // push var declaration back onto stack
						while(temp.size() > 0){ // while stack isnt empty 
							helperTree.add(temp.get(temp.size() - 1)); // push back all temp items back onto helperTree
						}
						helperTree.add(mdt); // push onto helper tree
						newTree.add(mdt); // push onto new tree
					}
					temp.add(m); // not var name so push onto temp stack to keep helperTree tokens & loop again
				}
				if(!found){ // var has not been defined
					System.out.println("ERROR: variable " + mdt.substring(mdt.lastIndexOf('-') + 2, mdt.length() - 1) + " has not been defined.");
					System.exit(0);
				}
			}
			if(mdt.equalsIgnoreCase("#END PARAGRAPH")){ // for static scoping of block code w/in para tag
				newTree.add(mdt); // just add to new tree - dont want on helper tree 
				do{
					m = helperTree.remove(helperTree.size() - 1);
				} while(!m.equalsIgnoreCase("#START PARAGRAPH"));
			}
			else
				newTree.add(mdt);
		}
		generateHtmlTags();
		printDoc();
	}
	
	public void generateHtmlTags(){
		for(int i = 0; i < newTree.size(); i ++){
			/* remove markdown tag token from parse tree (newTree)
			 *  then adding the token back into the tree with its html tag using the enum:
			class(Tags) method call .getN to get name of enum tag by passing its markdown tag */
			n = newTree.get(i); // get string value of markdown tag token
			o = Tags.getN(n); // get its html tag from its markdown tag
			newTree.remove(i);  // remove markdown tag
			if(o.equals(null) && n.contains("- ")) // token is use variable
				o = n.substring(n.lastIndexOf('-') + 2, n.length() - 1);
			else if(o.equals(null)) // token is just plain text
				o = n;
			
			newTree.add(i, o); // add html tag in tokens original spot
			
		}
	}
	
	public void printDoc(){
		for(int i = 0; i < newTree.size(); i ++)
			System.out.println(newTree.get(i));
	}

}




